<template>
  <div class="deviceWrapper">
    <el-row type="flex" align="middle">
      <el-col style="margin-left: 20px; margin-right: -20px" :span="2">设备标识:</el-col>
      <el-col :span="6">
        <el-input
          placeholder="请输入设备标识"
          v-model="deviceName" clearable>
        </el-input>
      </el-col>
      <el-col style="margin-left: 20px; margin-right: -20px" :span="2">设备IP:</el-col>
      <el-col :span="6">
        <el-input
          placeholder="请输入设备IP"
          v-model="deviceIp" clearable>
        </el-input>
      </el-col>
      <el-col style="margin-left: 20px; margin-right: -20px" :span="2">视频名称:</el-col>
      <el-col :span="6">
        <el-input
          placeholder="请输入视频名称"
          v-model="videoName" clearable>
        </el-input>
      </el-col>
    </el-row>
    <el-row style="margin-top: 12px" type="flex" align="middle">
      <el-col :span="6">&nbsp;</el-col>
      <el-col :span="18" style="text-align:right">
        <el-button type="primary" icon="el-icon-search" @click="searchBtn">搜索</el-button>
        <el-button type="success" icon="el-icon-close" @click="clearConditionBtn">清空条件</el-button>
      </el-col>
    </el-row>
    <div class="delete">
      <el-button type="primary" icon="el-icon-plus" @click="addBtn">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="deleteBtn">删除</el-button>
    </div>
    <el-table
      :height="tableHeight"
      @selection-change="selectChange"
      stripe
      :data="videoList"
      style="width: 100%;">
       <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="55">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        header-align="center"
        align="center"
        width="150">
      </el-table-column>
      <el-table-column
        label="视频名称"
        header-align="center"
        width="200"
        align="center">
        <template slot-scope="scope">
          <el-button @click="changeVideo(scope.row)" type="text">{{scope.row.videoName}}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="设备标识"
        prop="deviceName"
        header-align="center"
        align="center"
        width="200">
      </el-table-column>
      <el-table-column
        prop="deviceIp"
        label="设备IP"
        width="220"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        label="视频"
        header-align="center"
        width="100"
        align="center">
        <template slot-scope="scope">
            <el-button type="warning" icon="iconfont icon-play1" circle size="mini" @click="playVideo(scope.row.videoUrl)"></el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="标签"
        header-align="center"
        align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag 
              :type="scope.row.deviceId !== -1 ? 'primary' : 'success'"
              size="medium">{{ scope.row.deviceId === -1 ? '默认' : '自定义' }}</el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog title="新增视频" :visible.sync="dialogFormVisible" width="450px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-form :model="video">
        设备名称: <el-select v-model="video.deviceId" filterable placeholder="请选择设备">
          <el-option
            v-for="item in deviceList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-upload
          style="margin-top: 12px"
          class="upload"
          :action= "BASE_URL + '/v1/uploadVideo'"
          :on-remove="removeFile"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :limit="1"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过10G</div>
        </el-upload>
        <el-form-item label="视频名称:" :label-width="formLabelWidth">
          <el-input v-model="video.videoName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="sureAdd">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog  :visible.sync="dialogVideoVisible" @close="clodeVideo">
      <video-player  class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :playsinline="true"
          :options="playerOptions"
      ></video-player>
    </el-dialog>
  </div>
</template>

<script>
import { BASE_URL } from './../../api/config'
export default {
  data() {
    return {
      BASE_URL,
      videoList: [],
      videoName: '',
      videoUrl: '',
      deviceIp: '',
      deviceName: '',
      selection: [],
      deviceList: [],
      fileList: [],
      tableHeight: 0,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      dialogFormVisible: false,
      video: {
        id: '',
        deviceId: '',
        videoUrl: '',
        videoName: ''
      },
      formLabelWidth: '100px',
      dialogVideoVisible: false,
      // 视频播放
      playerOptions : {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "",
          src: ''
        }],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  //全屏按钮
        }
      }
    }
  },
  created() {
    this._getVideoList()
    this._getDeviceList()
    this.tableHeight = window.innerHeight - 425
  },
  components: {
  },
  methods: {
    _getVideoList() {
      this.$http.get("/v1/video",{
        deviceName: this.deviceName,
        deviceIp: this.deviceIp,
        videoName: this.videoName,
        videoUrl: this.videoUrl,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then((res) => {
        this.videoList = res.data
        this.total = res.total
      }).catch((errMsg) => {
        this.$message.error(errMsg)
      })
      this.selection = []
    },
    _getDeviceList() {
      this.$http.get("/v1/device",{
        pageNum: 1,
        pageSize: 100
      }).then((res) => {
        res.data.forEach((item) => {
          this.deviceList.push({
            value: item.id,
            label: item.deviceName
          })
        })
      }).catch((errMsg) => {
        this.$message.error(errMsg)
      })
    },
    selectChange(selection) {
      this.selection = selection
    },
    searchBtn() {
      this._getVideoList()
    },
    clearConditionBtn() {
      this.deviceName = ''
      this.deviceIp = ''
      this.videoUrl = ''
      this.videoName = ''
      this._getVideoList()
    },
    deleteBtn() {
      if(this.selection.length === 0){
        this.$message.error("请选择要删除的数据")
        return
      }
      let hasDefault = false
      this.selection.forEach(item => {
        if(item.deviceId === -1){
          this.$message.error("默认视频不允许删除")
          hasDefault= true
        }
      })
      if(hasDefault){
        return
      }
      this.$confirm('此操作将删除所选数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          this.selection.forEach(item => {
            ids.push(item.id)
          })
          this.$http.delete("/v1/video",{
            ids: ids.join(",")
          }).then((res) => {
            this.$message({
              message: '成功删除' + res.data + '条数据',
              type: 'success'
            })
            this.videoList = this.videoList.filter(video => ids.indexOf(video.id) === -1)
            this._getVideoList()
          }).catch((errMsg) => {
            this.$message.error(errMsg)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addBtn() {
      this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this._getVideoList()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this._getVideoList()
    },
    cancelAdd() {
      this.video.videoName = ''
      this.video.deviceId = ''
      this.video.videoUrl = ''
      this.video.id = ''
      this.fileList = []
      this.dialogFormVisible = false
    },
    sureAdd() {
      if(this.video.deviceId == null || this.video.deviceId === '' || this.video.videoName == null || this.video.videoName === '' || this.video.videoUrl == null || this.video.videoUrl === ''){
        this.$message.error('必填字段不能为空')
        return
      }
      if(this.video.id == null || this.video.id === ''){
        this.$http.post('/v1/video',{
          videoName: this.video.videoName,
          deviceId: this.video.deviceId,
          videoUrl: this.video.videoUrl
        }).then(() => {
          this.video.videoName = ''
          this.video.deviceId = ''
          this.video.videoUrl = ''
          this.video.id = ''
          this.fileList = []
          this.dialogFormVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this._getVideoList()
        }).catch((errMsg) => {
          this.$message.error(errMsg)
        })
      } else {
        this.$http.put('/v1/video',{
          id: this.video.id,
          videoName: this.video.videoName,
          deviceId: this.video.deviceId,
          videoUrl: this.video.videoUrl
        }).then(() => {
          this.video.videoName = ''
          this.video.deviceId = ''
          this.video.videoUrl = ''
          this.video.id = ''
          this.fileList = []
          this.dialogFormVisible = false
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this._getVideoList()
        }).catch((errMsg) => {
          this.$message.error(errMsg)
        })
      }
    },
    playVideo(url) {
      this.playerOptions.sources[0].src = url
      this.dialogVideoVisible = true
    },
    clodeVideo() {
      this.playerOptions.sources[0].src = ''
    },
    uploadSuccess (response) {
      this.video.videoUrl = response.data.downloadPath
      this.video.videoName = response.data.fileName
    },
    uploadError () {
      this.$message.error("视频上传失败,请稍后重试")
    },
    removeFile () {
      this.video.videoUrl = ''
      this.video.videoName = ''
    },
    changeVideo (video) {
      this.video.videoName = video.videoName
      this.video.videoUrl = video.videoUrl
      this.video.deviceId = video.deviceId
      this.video.id =  video.id
      this.fileList = [{
        name: video.videoName,
        url: video.videoUrl
      }]
      this.dialogFormVisible = true
    }
  }
}
</script>

<style scoped lang="stylus">
.deviceWrapper {
  z-index 20
}
.condition
  display flex
  flex-direction row
  align-items center
  justify-content space-between
  span
    margin-left 66px
    margin-right 12px
  .el-input
    width 300px
  .el-button
    margin-right 4px
.delete
  text-align left 
  margin-top 14px
  margin-bottom 12px
  margin-left 36px
.el-pagination
  margin-top 16px
  text-align right
</style>
